package yiran.depositcumulative.lister;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import yiran.depositcumulative.data.DatabaseService;
import yiran.gui.TopGUI;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class GUIListener implements Listener {
    private final Map<UUID, TopGUI> openGuis = new HashMap<>();
    private final DatabaseService databaseService;

    public GUIListener(DatabaseService databaseService) {
        this.databaseService = databaseService;
    }

    @EventHandler
    public void onInventoryClick(InventoryClickEvent event) {
        if (event.getWhoClicked() instanceof Player) {
            Player player = (Player) event.getWhoClicked();
            UUID uuid = player.getUniqueId();
            
            if (openGuis.containsKey(uuid)) {
                event.setCancelled(true); // 取消所有点击事件
                
                if (event.getRawSlot() < 54) { // 只处理GUI内的点击
                    openGuis.get(uuid).handleClick(event.getRawSlot(), player);
                }
            }
        }
    }

    @EventHandler
    public void onInventoryClose(InventoryCloseEvent event) {
        if (event.getPlayer() instanceof Player) {
            openGuis.remove(event.getPlayer().getUniqueId());
        }
    }
    
    // 打开排行榜GUI
    public void openTopGui(Player player) {
        TopGUI gui = new TopGUI(databaseService);
        openGuis.put(player.getUniqueId(), gui);
        gui.open(player);
    }
}
